import { cn } from "common-web";
import type { JSX } from "solid-js";
import { children, For, Index, Show, splitProps } from "solid-js";

type ListProps<T> = {
  header?: JSX.Element | undefined;
  footer?: JSX.Element | undefined;
  bordered?: boolean | undefined;
  dataSource?: T[] | undefined;
  renderItem?: (item: T, index: number) => JSX.Element | undefined;
  class?: string | undefined;
  style?: JSX.CSSProperties | string | undefined;
  useIndex?: boolean | undefined;
};

export default function List<T>(p: ListProps<T>) {
  const hasHeader = () => p.header !== undefined;
  const cHeader = children(() => p.header);

  const hasFooter = () => p.footer !== undefined;
  const cFooter = children(() => p.footer);

  const borderClass = () => p.bordered && "border border-gray-300 rounded-md shadow-sm";

  return (
    <div class={cn("w-full", borderClass(), p.class)} style={p.style}>
      <Show when={hasHeader()}>
        <div class="px-4 py-3 border-b border-gray-200">{cHeader()}</div>
      </Show>
      <div>
        <ul class="divide-y divide-gray-200">
          <Show when={p.useIndex}>
            <Index each={p.dataSource}>{(item, index) => p.renderItem?.(item(), index)}</Index>
          </Show>
          <Show when={!p.useIndex}>
            <For each={p.dataSource}>{(item, index) => p.renderItem?.(item, index())}</For>
          </Show>
        </ul>
      </div>
      <Show when={hasFooter()}>
        <div class="px-4 py-3 border-t border-gray-200">{cFooter()}</div>
      </Show>
    </div>
  );
}

type ListItemProps = JSX.LiHTMLAttributes<HTMLLIElement>;

export function ListItem(props: ListItemProps) {
  const [p, rest] = splitProps(props, ["class"]);
  return <li class={cn("py-2 px-4 hover:bg-gray-50 cursor-pointer", p.class)} {...rest} />;
}
